/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年10月27日
 */
package com.massyframework.beanskin.spring.boot.autoconfigure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.util.ClassUtils;

import com.massyframework.beanskin.framework.Framework;
import com.massyframework.beanskin.launcher.DefalutLauncher;

/**
 * BeanskinFramework启动Bean
 * @author huangkh
 *
 */
@Order(0)
public class BeanskinFrameworkInitializer 
	implements ApplicationContextInitializer<ConfigurableApplicationContext> {

	private Logger logger = LoggerFactory.getLogger(BeanskinFrameworkInitializer.class);
	
	private static final String WEB_APPLICATIONCONTEXT = "org.springframework.web.context.WebApplicationContext";
	/**
	 * 
	 */
	public BeanskinFrameworkInitializer() {
	}

	@Override
	public void initialize(ConfigurableApplicationContext applicationContext) {
		if (isAssignable(WEB_APPLICATIONCONTEXT, applicationContext.getClass())){
			//运行在Web环境下
			if (logger.isErrorEnabled()) {
				logger.error("spring boot run at WebApplication model, please use beanskin-spring-boot-starter-web.");
			}
			return;
		}
		
		applicationContext.addBeanFactoryPostProcessor(new FrameworkBeanDefinitionRegistryPostProcessor());
		this.launchFramework(applicationContext);
	}
	
	protected void launchFramework(ConfigurableApplicationContext applicationContext) {
		DefalutLauncher launcher = new DefalutLauncher();
		try {
			Framework framework = launcher.launch();
			framework.init();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getMessage(), e);
			}
		}
	}
	
	/**
	 * 判断{@code type}是否派生于{@code target}
	 * @param target
	 * @param type
	 * @return {@link boolean},返回{@code true}表示是，否则返回{@code false}
	 */
	private boolean isAssignable(String target, Class<?> type) {
		try {
			return ClassUtils.resolveClassName(target, null).isAssignableFrom(type);
		}
		catch (Throwable ex) {
			return false;
		}
	}
}
